<?php

namespace app\system\controller\business;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Trade;
use think\facade\Db;


class Quotation extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['product_name', 'corporate_name'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\business\Quotation;
    }

    public function test(): void {
        echo 1;die;
    }




    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $param = $this->request->param('state');

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
//            ->withJoin(['note'], $this->withJoinType)
            ->with(['note' => function($query){
                $query->with(['admin']);
            }])->alias($alias)
            ->where($where)
            ->where(['no' => $param['no'], 'filter_id' => $this->filter['id']]);

        if($param['type'] != -999){
            $res = $res->where(['hide' => $param['type']]);
        }
        if(!empty($param['corporate_name'])){
            $res = $res->where('corporate_name', 'like', '%' . $param['corporate_name'] . '%');
        }
        if(!empty($param['product_name'])){
            $res = $res->where('product_name', 'like', '%' . $param['product_name'] . '%');
        }

        $res = $res->order($order)->select();

        foreach($res as $key => $val){
            if(!empty($val['images'])){
                $arr = explode(',', $val['images']);
                $res[$key]['images'] = $arr;
            }
            $res[$key]['quotation_file'] = empty($val['quotation_file']) ? [] : json_decode($val['quotation_file'], true);
            $res[$key]['other_files'] = empty($val['other_files']) ? [] : json_decode($val['other_files'], true);
        }

        $business = db::name('business')->where(['no' => $param['no'], 'filter_id' => $this->filter['id']])->find();
        $business['product_images'] = empty($business['product_images']) ? [] : explode(',', $business['product_images']);
        $business['product_files'] = empty($business['product_files']) ? [] : json_decode($business['product_files'], true);
        $business['product_files_text'] = [];
        foreach($business['product_files'] as $key => $val){
            $business['product_files_text'][$key] = $val['url'];
        }

        $business['product_name'] = empty($business['product_name']) ? '' : html_entity_decode($business['product_name']);
//        foreach($business['product_images'] as $key => $val) $business['product_images'][$key] = 'http://localhost:8000' . $val;
        $this->success('', [
            'list' => $res,
//            'total' => $res->total(),
            'remark' => get_route_remark(),
            'info' => $business
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

//            if(!empty($data['images'])) $data['images'] = implode(',', $data['images']);
//            if(!empty($data['files'])) $data['files'] = implode(',', $data['files']);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['filter_id'] = $this->filter['id'];
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            if(empty($data['images'])){
                $data['images'] = null;
            }else{
                if(is_array($data['images'])){
                    $data['images'] = implode(',', $data['images']);
                }
            }
            $data['files'] = empty($data['files']) ? [] : $data['files'];
            $data['files'] = is_array($data['files']) ? $data['files'] : explode(',', $data['files']);
            $old_files = [];
            $new_files = [];
            $row['files'] = empty($row['files']) ? [] : json_decode($row['files'], true);
            foreach($data['files'] as $val){
                if(strstr($val, '/storage/default/')){
                    $new_files[] = $val;
                }else{
                    $old_files[] = $val;
                }
            }
            $files = [];
            foreach($row['files'] as $val){
                foreach($old_files as $v){
                    if($val['name'] == $v){
                        $files[] = $val;
                    }
                }
            }
            if($new_files){
                $attachment = db::name('attachment')->whereIn('url', $new_files)->select();
                foreach($attachment as $val){
                    $files[] = [
                        'id' => $val['id'],
                        'url' => $val['url'],
                        'name' => $val['name']
                    ];
                }
            }
            $data['files'] = json_encode($files);

            if(isset($data['quotation_file'])) unset($data['quotation_file']);
            if(isset($data['other_files'])) unset($data['other_files']);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 上传其他文件
     */
    public function setOtherFiles(): void{
        $param = $this->request->post();
        $update = [
            'other_files' => json_encode($param['other_files']),
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $param['id']])->update($update);
        $this->success();
    }


}